package dongshi.daddy.io.httpserver;

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer1 {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(8801);
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                service(socket);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void service(Socket socket) {
        String body = "hello,nio1";
        try {
            System.out.println("request come!!!");
            // 模拟耗时操作
            Thread.sleep(100);
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
            // 模拟http的响应，分为响应头和响应体（对象的组成也是头和体，不过是对象头和对象体），其中响应头和响应体通过换行符分割
            /*** 响应头开始 ***/
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Type:text/html;charset=utf-8");
            // 注意一定要有该内容告知客户端响应体的长度，不然客户端将无法正常读取数据
            printWriter.println("Content-Length:" + body.getBytes().length);
            // 空行结束响应头
            printWriter.println();
            /*** 响应头结束 ***/

            /*** 响应体开始 ***/
            printWriter.write(body);
            /*** 响应体结束 ***/
//            printWriter.flush();
            printWriter.close();
            socket.close();
        } catch (Exception e) {
        }
    }
}
